﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interactivity;

namespace Albatross.WPF.Common.Views {
	//allow view model to send a message to the view
	public delegate void ViewModelMessageDelegate(object sender, string topic, object args);

	public class ViewModelMessenger : Behavior<FrameworkElement> {
		public event ViewModelMessageDelegate Received;

		void OnReceived(object sender, string topic, object args) {
			var handler = Received;
			if (handler != null) { handler(sender, topic, args); }
		}

		protected override void OnAttached() {
			((FrameworkElement)AssociatedObject).DataContextChanged += ViewModelEventBehavior_DataContextChanged;
			base.OnAttached();
		}
		protected override void OnDetaching() {
			((FrameworkElement)AssociatedObject).DataContextChanged -= ViewModelEventBehavior_DataContextChanged;
			MessageHandler = null;
			base.OnDetaching();
		}

		void ViewModelEventBehavior_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) {
			MessageHandler = OnReceived;
		}

		public const string MessageHandlerPropertyName = "MessageHandler";
		public static readonly DependencyProperty MessageHandlerProperty = DependencyProperty.Register(MessageHandlerPropertyName, typeof(ViewModelMessageDelegate), typeof(ViewModelMessenger), new PropertyMetadata());
		public ViewModelMessageDelegate MessageHandler {
			get { return (ViewModelMessageDelegate)GetValue(MessageHandlerProperty); }
			set { SetValue(MessageHandlerProperty, value); }
		}
	}
}
